<!--
 * @Date: 2025-02-02 19:30:33
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-02-13 09:21:57
 * @FilePath: /vue3-admin/src/views/common/LoginView.vue
-->
<script setup lang="ts">
import { useSettingsStore, usePermissionStore } from '@/store';
import { Sunny, Moon } from '@element-plus/icons-vue';
import {
    type LocationQuery,
    type LocationQueryValue,
    useRoute
} from 'vue-router';
import router from '@/router';
import defaultSettings from '@/settings';
import { ThemeEnum } from '@/enums/ThemeEnum';
import { useLogin, LoginParam } from '@/service/useLogin';
import { useRules } from '@/service/useRules';

// Stores
const permissionStore = usePermissionStore();
const settingsStore = useSettingsStore();

// Reactive states
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
const icpVisible = ref(true);
const loading = ref(false); // 按钮loading
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串
const loginFormRef = ref(ElForm); // 登录表单ref
const { height } = useWindowSize();

const loginParam = ref(new LoginParam());
const { generateCaptchaUrl, loginByPassword } = useLogin();

const { requiredRule } = useRules();
const loginRules = computed(() => {
    return {
        username: [...requiredRule],
        password: [...requiredRule],
        captcha: [...requiredRule]
    };
});

/** 获取验证码 */
function getCaptcha() {
    captchaBase64.value = generateCaptchaUrl();
}

/** 登录 */
const route = useRoute();
function handleLogin() {
    loginFormRef.value.validate((valid: boolean) => {
        if (valid) {
            loading.value = true;
            loginByPassword(loginParam.value)
                ?.then((res) => {
                    permissionStore.needUpdate = true;
                    const query: LocationQuery = route.query;
                    const redirect =
                        (query.redirect as LocationQueryValue) ?? '/';
                    const otherQueryParams = Object.keys(query).reduce(
                        (acc: any, cur: string) => {
                            if (cur !== 'redirect') {
                                acc[cur] = query[cur];
                            }
                            return acc;
                        },
                        {}
                    );
                    router.push({ path: redirect, query: otherQueryParams });
                    return res;
                })
                .catch((err) => {
                    getCaptcha();
                    return Promise.reject(err);
                })
                .finally(() => {
                    loading.value = false;
                });
        }
    });
}

/** 主题切换 */
const toggleTheme = () => {
    const newTheme =
        settingsStore.theme === ThemeEnum.DARK
            ? ThemeEnum.LIGHT
            : ThemeEnum.DARK;
    settingsStore.changeTheme(newTheme);
};

/** 根据屏幕宽度切换设备模式 */
watchEffect(() => {
    if (height.value < 600) {
        icpVisible.value = false;
    } else {
        icpVisible.value = true;
    }
});

onMounted(() => {
    getCaptcha();
});
</script>

<template>
    <div class="login-container">
        <!-- 顶部 -->
        <div class="absolute-lt flex-x-end p-3 w-full z-10">
            <el-switch
                v-model="isDark"
                inline-prompt
                :active-icon="Moon"
                :inactive-icon="Sunny"
                @change="toggleTheme"
            />
            <lang-select class="ml-2 cursor-pointer" />
        </div>

        <div
            class="absolute inset-t-0 mx-auto mt-[30px] flex flex-row items-center z-10"
        >
            <img
                src="@/assets/images/logo.png"
                class="w-[100px] h-p[100px] mr-[20px]"
            />
            <div class="flex flex-row max-w-[1000px] text-center">
                <span class="c-[#0777FF] dark:c-[#ffffff] text-6xl">{{
                    $t('app.title')
                }}</span>
                <el-tag class="ml-2">{{ defaultSettings.version }}</el-tag>
            </div>
        </div>

        <!-- 登录表单 -->
        <el-card
            class="!border-none !rounded-4% w-100 <sm:w-85 z-10 bg-white dark:bg-black"
        >
            <!-- <div class="text-center relative">
                <h2>{{ defaultSettings.title }}</h2>
                <el-tag class="ml-2 absolute-rt">{{
                    defaultSettings.version
                }}</el-tag>
            </div> -->
            <el-form
                ref="loginFormRef"
                :model="loginParam"
                :rules="loginRules"
                class="login-form"
            >
                <!-- 用户名 -->
                <el-form-item prop="username">
                    <div class="flex-y-center w-full">
                        <svg-icon icon-class="user" class="mx-2" />
                        <el-input
                            ref="username"
                            v-model="loginParam.username"
                            :placeholder="$t('login.username')"
                            name="username"
                            size="large"
                            class="h-[48px]"
                        />
                    </div>
                </el-form-item>

                <!-- 密码 -->
                <el-tooltip
                    :visible="isCapslock"
                    :content="$t('login.capsLock')"
                    placement="right"
                >
                    <el-form-item prop="password">
                        <div class="flex-y-center w-full">
                            <svg-icon icon-class="lock" class="mx-2" />
                            <el-input
                                v-model="loginParam.password"
                                :placeholder="$t('login.password')"
                                type="password"
                                name="password"
                                @blur="
                                    () => {
                                        isCapslock = false;
                                    }
                                "
                                @keydown="
                                    (event) => {
                                        if (
                                            typeof (event as KeyboardEvent)
                                                .getModifierState === 'function'
                                        ) {
                                            isCapslock = (
                                                event as KeyboardEvent
                                            ).getModifierState('CapsLock');
                                        }
                                    }
                                "
                                @keyup="
                                    (event: KeyboardEvent) => {
                                        if (
                                            typeof (event as KeyboardEvent)
                                                .getModifierState === 'function'
                                        ) {
                                            isCapslock =
                                                event.getModifierState(
                                                    'CapsLock'
                                                );
                                        }
                                    }
                                "
                                @keyup.enter="handleLogin"
                                size="large"
                                class="h-[48px] pr-2"
                                show-password
                            />
                        </div>
                    </el-form-item>
                </el-tooltip>

                <!-- 验证码 -->
                <el-form-item prop="captcha">
                    <div class="flex-y-center w-full">
                        <svg-icon icon-class="captcha" class="mx-2" />
                        <el-input
                            v-model="loginParam.captcha"
                            auto-complete="off"
                            size="large"
                            class="flex-1"
                            :placeholder="$t('login.captchaCodePlaceholder')"
                            @keyup.enter="handleLogin"
                        />

                        <el-image
                            @click="getCaptcha"
                            :src="captchaBase64"
                            class="rounded-tr-md rounded-br-md cursor-pointer h-[48px]"
                        />
                    </div>
                </el-form-item>

                <!-- 登录按钮 -->
                <el-button
                    :loading="loading"
                    type="primary"
                    size="large"
                    class="w-full"
                    @click.prevent="handleLogin"
                    >{{ $t('login.login') }}
                </el-button>

                <!-- 账号密码提示 -->
                <!-- <div class="mt-10 text-sm">
                    <span>{{ $t('login.username') }}: admin</span>
                    <span class="ml-4">
                        {{ $t('login.password') }}: 123456</span
                    >
                </div> -->
            </el-form>
        </el-card>

        <!-- ICP备案 -->
        <!-- <div
            class="absolute bottom-1 text-[10px] text-center z-10"
            v-show="icpVisible"
        >
            <p>
                Copyright © 2021 - 2024 youlai.tech All Rights Reserved.
                有来技术 版权所有
            </p>
            <p>皖ICP备20006496号-3</p>
        </div> -->
    </div>
</template>

<style lang="scss" scoped>
html.dark .login-container {
    background: url('@/assets/images/login-bg-dark.jpg') no-repeat center right;

    &::before {
        position: absolute;
        top: 0;
        left: 0;
        display: block;
        width: 100%;
        height: 100%;
        content: '';
        background: url('@/assets/images/front-login-bg.png') no-repeat center
            center;
        background-size: 100%;
    }
}

.login-container {
    overflow-y: auto;
    background: url('@/assets/images/login-bg.jpg') no-repeat center right;

    @apply wh-full flex-center;

    &::before {
        position: absolute;
        top: 0;
        left: 0;
        display: block;
        width: 100%;
        height: 100%;
        content: '';
        background: url('@/assets/images/front-login-bg.png') no-repeat center
            center;
        background-size: 100%;
    }

    .login-form {
        padding: 30px 10px;
    }
}

.el-form-item {
    background: var(--el-input-bg-color);
    border: 1px solid var(--el-border-color);
    border-radius: 5px;
}

:deep(.el-input) {
    .el-input__wrapper {
        padding: 0;
        background-color: transparent;
        box-shadow: none;

        &.is-focus,
        &:hover {
            box-shadow: none !important;
        }

        input:-webkit-autofill {
            /* 通过延时渲染背景色变相去除背景颜色 */
            transition: background-color 1000s ease-in-out 0s;
        }
    }
}
</style>
